<?php

class Car extends CActiveRecord
{
	/**
	 * The followings are the available columns in table 'cat_models':
	 * @var integer $id
	 * @var integer $brand_id
	 * @var integer $family_id
	 * @var integer $archive
	 * @var integer $classmate_id
	 * @var string $title
	 * @var string $alias
	 * @var integer $concept
	 * @var string $description
	 * @var string $description_marked
	 * @var string $manufacture_start
	 * @var string $manufacture_end
	 */
	public $RU_NAME = 'Модель';
	
	public $_gallery = array();

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'cat_models';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('_gallery', 'file', 'types'=>'zip', 'allowEmpty'=>true),
		
			array('alias', 'unique'),
			array('brand_id, title, alias, manufacture_start', 'required'),
			array('concept', 'boolean'),
			array('brand_id, family_id, archive, classmate_id, comments_count', 'numerical', 'integerOnly'=>true),
			array('title, alias', 'length', 'max'=>60),
			array('description, description_marked, manufacture_start, manufacture_end', 'safe'),
			array('manufacture_end', 'default', 'setOnEmpty'=>'null'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, brand_id, family_id, archive, classmate_id, title, alias, description, manufacture_start, manufacture_end', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'family'=>array(self::BELONGS_TO, 'Family', 'family_id'),
			'brand'=>array(self::BELONGS_TO, 'Brand', 'brand_id'),
			'modifications'=>array(self::HAS_MANY, 'Modification', 'model_id'),
		
			'galleries'=>array(self::MANY_MANY, 'Gallery', 'cat_models_galleries(model_id, gallery_id)'),
			
			'comments'=>array(self::HAS_MANY, 'Comment', 'object_id', 'condition'=>'comments.type='.Lookup::ritem('CommentType',__CLASS__)),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'brand_id' => 'Бренд',
			'family_id' => 'Семейство',
			'archive' => 'Архив',
			'classmate_id' => 'Одноклассники',
			'title' => 'Название',
			'alias' => 'Псевдоним',
			'concept' => 'Концепт',
			'description' => 'Описание',
			'description_marked' => 'Описание',
			'manufacture_start' => 'Начало производства',
			'manufacture_end' => 'Окончание производства',
			'comments_count' => 'Количество комментариев',
		
			'_gallery' => 'Галереи',
			'comments' => 'Комментарии',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);

		$criteria->compare('brand_id',$this->brand_id);

		$criteria->compare('family_id',$this->family_id);

		$criteria->compare('archive',$this->archive);

		$criteria->compare('classmate_id',$this->classmate_id);

		$criteria->compare('title',$this->title,true);

		$criteria->compare('alias',$this->alias,true);
		
		$criteria->compare('description',$this->description,true);

		$criteria->compare('manufacture_start',$this->manufacture_start,true);

		$criteria->compare('manufacture_end',$this->manufacture_end,true);

		return new CActiveDataProvider('Car', array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>Yii::app()->params['linesPerPage'],
			),
		));
	}
	
	public function afterDelete(){
		# Проверка и очистка связей
		$modifications = Modification::model()->findAll('model_id=:model_id', array(':model_id'=>$this->id));
		if(count($modifications)>0)
			foreach($modifications as $modification)
				$modification->delete();
		
		Comment::model()->deleteAll('object_id=:object_id and type='.Lookup::ritem('CommentType',__CLASS__),array(':object_id'=>$this->id));
		
		return parent::afterDelete();
	}
	
	public function afterFind(){
		parent::afterFind();
		
		if(!empty($this->galleries)){
			foreach($this->galleries as $gallery){
				$this->_gallery[$gallery->id] = array(
					'id'=>$gallery->id,
					'title'=>$gallery->title,
					'url'=>Yii::app()->createUrl('admin/galleries/view', array('id'=>$gallery->id)),
				);
			}
		}
	}
	
	public function beforeSave(){
		if(AController::_user()->profile->editor == 0){
			if($this->description) {
				Yii::import('ext.markdown.*');
				$md = new EMarkdown;
				$this->description_marked = $md->transform($this->description);
			}
		}
		
		return parent::beforeSave();
	}
	
	public function afterSave(){
		$this->saveGallery();
		return parent::afterSave();
	}
	
	public function saveGallery(){
		#EDebug::d($this->_gallery);
		CarsGalleries::model()->deleteAll('model_id=:model_id', array(':model_id'=>$this->id));		
		
		foreach($this->_gallery as $i=>$gallery){
			#EDebug::d(CUploadedFile::getInstance($this, '_gallery['.$i.']'));
			if(isset($gallery['id']) && $g = Gallery::model()->findByPK($gallery['id'])){
				$g->title = CHtml::encode($gallery['title']);
				$g->save();
				$ag = new CarsGalleries;
				$ag->model_id = $this->id;
				$ag->gallery_id = $g->id;
				$ag->save();
			} elseif(isset($gallery['title']) && $arc = CUploadedFile::getInstance($this, '_gallery['.$i.']') ) {
				$zip = Yii::app()->zip;
				$alias = Gallery::model()->createAlias($this->alias);
				$path = Yii::getPathOfAlias(Yii::app()->params['paths']['galleries']['path']).DIRECTORY_SEPARATOR.$alias.DIRECTORY_SEPARATOR;
				$tmp_path =  Yii::app()->file->set($path.uniqid().DIRECTORY_SEPARATOR);

				if($zip->extractZip($arc->tempName, $tmp_path->realpath)){
					$files = $tmp_path->contents;
					#EDebug::d($files);
					$g = new Gallery;
					$g->title = CHtml::encode($gallery['title']);
					$g->alias = $alias;
					$g->save();
					foreach($files as $i=>$file){
						$image = Image::addFile( $file, basename($file), $path, Gallery::$_sizes, $this->title, $this->title);
						$gi = new GalleriesImages;
						$gi->gallery_id = $g->id;
						$gi->filename = $image;
						$gi->ord = $i;
						$gi->save();
					}
					$ag = new CarsGalleries;
					$ag->model_id = $this->id;
					$ag->gallery_id = $g->id;
					$ag->save();
				}
				$tmp_path->delete();
			}
		}
	}
}